package demo.dcs.aspect;

import demo.dcs.MertricSendSchedule;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;

import java.lang.reflect.Field;


/**
 * @author mandy.hu
 *
 */
public class RedisPoolAspectJ2 extends AbstractXdcsAspectJ{

	private static final Logger logger = LoggerFactory.getLogger(RedisPoolAspectJ2.class);

    @Override
	public void beforeAspectJ(Object signature, Object instance, Object[] args) {
	}

	@Override
	public void afterAspectJ(Object result, Object signature, Object instance, Object[] args, Throwable throwable) {
		try {
			if (!mercurySwitch()) {
				return;
			}
			if (instance instanceof JedisPool && args.length ==7) {
				JedisPool pool = (JedisPool)instance;
				StringBuilder stringBuilder = new StringBuilder();
                if (args[1] instanceof String) {
                    stringBuilder.append(args[1]).append(":");
                }
                if (args[2] instanceof Integer) {
                    stringBuilder.append(args[2]);
                }
                if (args[5]!=null && args[5] instanceof Integer){
                    stringBuilder.append("-").append(args[5]);
                }
				String hostString = stringBuilder.toString();
				Field field = JedisPoolFieldsCache.getInstance().getInternalPoolFiled();
                try {
                    GenericObjectPool genericObjectPool2 = (GenericObjectPool) field.get(pool);
                    if (genericObjectPool2!=null){
                        MertricSendSchedule.getMertricSendSchedule().addMertricListener(new GenericObjectPool2Listener(genericObjectPool2, hostString));
                    }
                }catch (Throwable e){
                    logger.warn("RedisPoolAspectJ2 afterAspectJ get genericObjectPool error", e);
                }
			}
		} catch (Exception e) {
			logger.error("RedisPoolAspectJ2 afterAspectJ", e);
		}
	}
}
